package com.syedu.day18;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.Arrays;

/**
 * @author Administrator
 * @Description Java反射操作构造方法
 * @createTime 2022/4/11 9:34
 */
public class ConstructorReflect {
    public static void main(String[] args) {
        Class<Point> c = Point.class;

        //获取类中所有的构造方法
        Constructor[] constructors = c.getConstructors();//获取所有公开构造方法
        //Constructor[] constructors = c.getDeclaredConstructors();//获取所有的构造方法

        for (Constructor constructor : constructors) {
            //System.out.println(constructor);
            //获取构造方法的修饰符
            String modifier = Modifier.toString(constructor.getModifiers());
            //获取构造方法的名字
            String name = constructor.getName();
            //获取构造方法的参数
            Class[] parameterTypes = constructor.getParameterTypes();

            String result = modifier + " " + name.substring(name.lastIndexOf(".") + 1) + "(";
            if (parameterTypes != null && parameterTypes.length > 0) {
                for (int i = 0; i < parameterTypes.length; i++) {
                    result += i == parameterTypes.length - 1 ? parameterTypes[i].getName() : parameterTypes[i].getName() + ",";
                }
            }
            result += "){}";
            System.out.println(result);
        }

        System.out.println("-------------------------------------------------------");

        /**
         * 反射创建对象(开发一定会用到!!!)
         */
        try {
            //1.调用空参构造创建对象
            //JDK9.0开始过时
            Point p1 = c.newInstance();

            //Point p2 = c.getConstructor(new Class[]{}).newInstance(new Object[]{});
            Point p2 = c.getConstructor().newInstance();
            System.out.println(p1);
            System.out.println(p2);

            //2.调用有参构造创建对象
            //Point p3 = c.getConstructor(new Class[]{int.class, int.class}).newInstance(new Object[]{10, 20});
            Point p3 = c.getConstructor(int.class, int.class).newInstance(10, 20);
            System.out.println(p3);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
